import axios from 'axios'; // 引入axios
import qs from 'qs'; // 引入qs
import Global from './global'; // 引入global.js
import Vue from 'vue';
import { Message } from 'element-ui';
import i18n from '../locale/index'

// axios 默认配置  更多配置查看Axios中文文档
axios.defaults.timeout = 60000; // 设置超时值1分钟
axios.defaults.headers.common['Content-Type'] = 'application/json;charset=UTF-8';


//登录标识位置
var loginInx = location.href.indexOf('/login?');
//截取参数 , 截取问号后面的字符串
var queryString = location.href.substring(location.href.indexOf(location.origin) + location.origin.length + 1).split('?');
var queryArr = is_empty(queryString[1]) ? '' : queryString[1].split('&');
var queryObj = {};
var isLock = false; //短时间防止重复触发


//参数组合对象
for (var i = queryArr.length - 1; i >= 0; i--) {
  var temp = queryArr[i].split('=');
  queryObj[temp[0]] = temp[1];
}
if (loginInx > -1) {
  //登录token是否空
  if (is_empty(queryObj.token)) {
    queryObj.token = '--';
  }
  sessionStorage.setItem('token', queryObj.token);
  delete queryObj.token;
}
var redirectUrl = '/login?token=' + queryObj.token;
//请求服务器host字段为空,则使用当前地址的host
if (!is_empty(queryObj.host)) {
  sessionStorage.setItem('host', queryObj.host);
  redirectUrl += '&host=' + queryObj.host;
  delete queryObj.host;
} else if (is_empty(sessionStorage.getItem('host'))) {
  sessionStorage.setItem('host', location.host);
  redirectUrl += '&host=' + location.host;
}


//设置websocket请求地址
var ip = sessionStorage.getItem('host').split(":");
sessionStorage.setItem('user_chat_url', 'ws://' + ip[0] + ':7272')


//请求服务器procotol字段为空,则使用当前地址的procotol
if (!is_empty(queryObj.protocol)) {
  sessionStorage.setItem('protocol', queryObj.protocol);
  redirectUrl += '&protocol=' + queryObj.protocol;
  delete queryObj.protocol;
} else if (is_empty(sessionStorage.getItem('protocol'))) {
  sessionStorage.setItem('protocol', location.protocol.replace(':', ''));
  redirectUrl += '&procotol=' + location.protocol.replace(':', '');
}


//设置跳转其他内部平台的地址 例如 后台,个人中心
sessionStorage.setItem('redirect_params', '/login?token=' + sessionStorage.getItem('token'));
//设置请求地址
const apiUrl = sessionStorage.getItem('protocol') + '://' + sessionStorage.getItem('host');
sessionStorage.setItem('host_addr', apiUrl);
getAccessToken(apiUrl);

if (!is_empty(queryObj.ItcJwtToken)) {
  sessionStorage.setItem('ItcJwtToken', queryObj.ItcJwtToken);
  delete queryObj.ItcJwtToken;
}
if (!is_empty(queryObj.CheckSchoolAppCode)) {
  sessionStorage.setItem('CheckSchoolAppCode', queryObj.CheckSchoolAppCode);
  delete queryObj.CheckSchoolAppCode;
}

/** 
    PS 登录时必须要携带的参数 token 在登录时有效的参数 CheckSchoolAppCode ItcJwtToken
       其他参数作为跳转到相应模块的参数用paramString来存储,约定 routerUrl 为跳转的路由
*/
var paramString = '';
//模块字符串
var moduleString = '';
var urlString = location.href.substring(location.href.indexOf(location.origin) + location.origin.length + 1);

// 如果endInx==-1表示url中没有查询参数，反则有查询参数
var endInx = urlString.indexOf('?');

// urlStringObj为初始加载网页是的路由
if (endInx === -1) {
  var urlStringObj = [urlString];
} else {
  var urlStringObj = urlString.substring(0, endInx).split('/');
}

// 若果值为空代表url中没有路由
if (is_empty(urlStringObj[0]) || urlStringObj[0] == 'user-login') {
  if (is_empty(queryObj.routerUrl)) {
    moduleString = 'logintable';
    paramString = '/' + moduleString;
  } else {
    moduleString = queryObj.routerUrl.split('/')[0];
    paramString = queryObj.routerUrl;
  }
} else if (urlStringObj[0] == 'register') {
  moduleString = 'logintable';
  paramString = '/' + moduleString;
} else {
  moduleString = urlStringObj[0];
  paramString = '/' + moduleString;
}
sessionStorage.setItem('decisionPlatform', moduleString);
//剩下的参数作为跳转的参数
paramString += Object.keys(queryObj).length === 0 ? '' : '?';
let inx = 0;
delete queryObj.routerUrl;
Object.keys(queryObj).forEach(function (key) {
  paramString += (inx === 0 ? '' : '&') + key + '=' + queryObj[key];
  inx++;
})
sessionStorage.setItem('paramString', paramString);

Global.decisionPlatform = sessionStorage.getItem('decisionPlatform');

axios.defaults.baseURL = sessionStorage.getItem('host_addr')
// http request 拦截器
// 在ajax发送之前拦截 比如对所有请求统一添加header token
var company = 'BL';
var device_name = 'TE-0600R';
axios.interceptors.request.use(
  config => {
    if (Global.access_token) {
      // 视频分享页面地址栏上有的video_sign参数，要在请求播放地址的时候，替换视频id参数，去拿视频地址
      const video_sign = sessionStorage.getItem('video_sign'),
        resource_sign = sessionStorage.getItem('resource_sign'),
        album_sign = sessionStorage.getItem('album_sign'),
        live_sign = sessionStorage.getItem('live_sign');
      if (video_sign || resource_sign || album_sign || live_sign) {
        config.headers.SharePage = true;
      }
      config.headers.Authorization = `Bearer ${Global.access_token}`;
      config.headers.DecisionPlatform = sessionStorage.getItem('decisionPlatform');
      config.headers.token = sessionStorage.getItem('token') === '--' ? null : sessionStorage.getItem('token');
      config.headers.ItcJwtToken = sessionStorage.getItem('ItcJwtToken');
      config.headers.CheckSchoolAppCode = sessionStorage.getItem('CheckSchoolAppCode')
      var actioncodeArr = config.url.split('/');

      if (config.method == 'post' || config.method == 'put') {
        if (!config.data.hasOwnProperty('company')) {
          if (config.headers['content-type'] != 'multipart/form-data') {
            var requestData = config.data;
            delete config.data;
            config.data = {};
            config.data.company = company;
            config.data.device_name = device_name;
            config.data.sign = `${Global.access_token}`;
            config.data.actioncode = config.method + '_' + actioncodeArr[actioncodeArr.length - 1];
            config.data.data = requestData;
            config.data = qs.stringify(config.data);
          }
        }

      } else if (config.method == 'get' || config.method == 'delete') {
        if (config.params === undefined) {
          config.params = {};
        }
        if (!config.params.hasOwnProperty('company')) {
          var requestData = config.params;
          delete config.params;
          config.params = {};
          config.params.company = company;
          config.params.device_name = device_name;
          config.params.sign = `${Global.access_token}`;
          config.params.actioncode = config.method + '_' + actioncodeArr[actioncodeArr.length - 1];
          config.params.data = requestData;
        }
      }
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);

// http response 拦截器
// ajax请求回调之前拦截 对请求返回的信息做统一处理 比如error为401无权限则跳转到登陆界面
axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  if (!response.config.hasOwnProperty('func')) {
    response.config.func = {};
  }
  if (response.data.hasOwnProperty('data')) {
    var responseData = handleResponseData(response.data, 'need');
  } else {
    var responseData = response.data;
  }
  // 对响应数据做点什么
  Vue.prototype.Ajax_callback(responseData, response.config.func)
  return response;
}, function (error) {
  // console.info(error);
  //超时响应
  if (error.message.indexOf('timeout') > -1) {
    Vue.prototype.Ajax_callback({
      status: 'timeout',
      msg: i18n.t('response.timeOut')
    }, error.config.func);
    return false;
  } else if (error.response.status == 401) {
    var config = error.config;
    get_access_token(function () {
      //重新发送请求，并执行回调

      if (config.method == 'post' || config.method == 'put') {
        //qs.stringify反向转换成对象

        config.data = qs.parse(config.data);
      }
      if (!config.hasOwnProperty('func')) {
        config.func = {};

      }
      //执行之前的ajax请求
      axios(config).then(response => Vue.prototype.Ajax_callback(response.data, config.func));
    });

  } else if (error.response.status == 505) {
    if (isLock) return;
    isLock = true;
    Message.closeAll();
    Message.error(i18n.t('global.pleaseSignIn'))

    let SharePath = sessionStorage.getItem('sharePath')

    sessionStorage.clear();
    localStorage.clear();

    sessionStorage.setItem('sharePath', SharePath)

    setTimeout(() => {
      const loginPagePath = `${location.origin}/user-login`
      window.location.href = loginPagePath;
      isLock = false;
    }, 2000)

  } else if (error.response.status == 506) {
    //506说明ItcJwtToken已更改
    // console.log(getCookie(itc_jwt_token))
    let ItcJwtToken = getCookie(itc_jwt_token);
    sessionStorage.setItem('ItcJwtToken', ItcJwtToken);
    setTimeout(() => {
      window.location.reload();
    }, 1500)
  } else if (error.response.status == 606) {
    // 606跳cdkey页面
    window.location.href = location.protocol + '//' + location.host + '/cdkey';
  } else {
    // 对响应数据做点什么
    if (!error.response.config.hasOwnProperty('func')) {
      error.response.config.func = {};
    }
    Vue.prototype.Ajax_callback(error.response.data, error.response.config.func)

  }
  return Promise.reject(error);
});

export default axios; // 这句千万不能漏下！！！

/**
 * 获取access_token 方法封装
 */
function get_access_token(callback) {
  axios.get('/accessToken', {
    params: {
      company: 'BL',
      device_name: 'TE-0600R',
      data: {
        client_id: Global.client_id,
        secret: Global.secret
      }
    }
  })
    .then(response => {
      let data = response.data.data;
      Global.access_token = data.access_token;
      localStorage.setItem('access_token', Global.access_token);
      callback();
    });
}

/**
 * 获取cookie里某个键的值
 */
function getCookie(name) {
  var strcookie = document.cookie; //获取cookie字符串
  var arrcookie = strcookie.split("; "); //分割
  //遍历匹配
  for (var i = 0; i < arrcookie.length; i++) {
    var arr = arrcookie[i].split("=");
    if (arr[0] == name) {
      return arr[1];
    }
  }
  return "";
}

function getAccessToken(apiUrl) {
  axios.get(`${apiUrl}/accessToken`, {
    params: {
      company: 'BL',
      device_name: 'TE-0600R',
      data: {
        client_id: Global.client_id,
        secret: Global.secret
      }
    }
  })
    .then(response => {
      let data = response.data.data;
      Global.access_token = data.access_token;
      localStorage.setItem('access_token', Global.access_token);
    });
}
